package com.example.othree.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.othree.common.PageParam;
import com.example.othree.common.R;
import com.example.othree.entity.*;
import com.example.othree.entity.Aot40HistoryDayDataHsxt;
import com.example.othree.service.Aot40HistoryDayDataHsxtService;
import com.example.othree.service.WeatherStationInfoService;
import com.example.othree.service.WheatCornGrowthYearService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zogran
 * @since 2024-11-12
 */
@RestController
@CrossOrigin
@RequestMapping("/api")
public class Aot40HistoryDayDataHsxtController {
    @Autowired
    private Aot40HistoryDayDataHsxtService aot40HistoryDayDataService;

    @Autowired
    private WheatCornGrowthYearService wheatCornGrowthService;

    @Autowired
    private WeatherStationInfoService weatherStationInfoService;


    @PostMapping("/Aot40/create")
    @ApiOperation("新增")
    public R create(@RequestBody Aot40HistoryDayDataHsxt aot40HistoryDayDataHsxt){
        return aot40HistoryDayDataService.save(aot40HistoryDayDataHsxt) ? R.ok() : R.error();
    }

    @PostMapping("/Aot40/saveBatch")
    @ApiOperation("批量新增")
    public R saveBatch(@RequestBody List<Aot40HistoryDayDataHsxt> aot40HistoryDayDataHsxtList){
        return aot40HistoryDayDataService.saveBatch(aot40HistoryDayDataHsxtList) ? R.ok() : R.error();
    }

    @GetMapping("/Aot40/list")
    public List<Aot40HistoryDayDataHsxt> list(){
        return aot40HistoryDayDataService.list();
    }

    @PostMapping("/Aot40/update")
    @ApiOperation("修改")
    public R update(@RequestBody Aot40HistoryDayDataHsxt aot40HistoryDayDataHsxt){
        return aot40HistoryDayDataService.updateById(aot40HistoryDayDataHsxt) ? R.ok() : R.error();
    }

    @PostMapping("/Aot40/delete/{id}")
    public R delete(@PathVariable Integer id){
        return aot40HistoryDayDataService.removeById(id) ? R.ok() : R.error();
    }

    @PostMapping("/Aot40/listPage")
    @ApiOperation("查询、分页")
    public R listPage(@RequestBody PageParam pageParam){
        HashMap param = pageParam.getParam();
        String county = param.get("county").toString();
        String city = param.get("city").toString();
        String date = param.get("date").toString();

        Page<Aot40HistoryDayDataHsxt> page = new Page();
        page.setCurrent(pageParam.getPageNum());
        page.setSize(pageParam.getPageSize());

        LambdaQueryWrapper<Aot40HistoryDayDataHsxt> lambdaQueryWrapper = new LambdaQueryWrapper();

        if(StringUtils.isNotBlank(county) && !"null".equals(county)){
            lambdaQueryWrapper.eq(Aot40HistoryDayDataHsxt::getCounty, county);
        }
        if(StringUtils.isNotBlank(city) && !"null".equals(city)){
            lambdaQueryWrapper.eq(Aot40HistoryDayDataHsxt::getCity, city);
        }
        if(StringUtils.isNotBlank(date) && !"null".equals(date)){
            lambdaQueryWrapper.eq(Aot40HistoryDayDataHsxt::getDate, date);
        }

        IPage result = aot40HistoryDayDataService.PageList(page, lambdaQueryWrapper);

        return R.ok().data("result", result);
    }

    @GetMapping("/O3-space-data")
    @ApiOperation("获取臭氧对农作物影响指标空间数据")
    public R Aot40OrO3ByGrowth(@RequestParam("city") String city,
                                        @RequestParam("element") String element,
                                        @RequestParam("year") String year,
                                        @RequestParam("crop") String crop,
                                        @RequestParam("dataDecision") String dataDecision,
                                        @RequestParam("startPeriod") String startPeriod, @RequestParam("endPeriod") String endPeriod){
        HashMap<String, Object> result = new HashMap<>();
        try {
            List<Aot40HistoryDayDataHsxt> dataList;
            if(element.equals("AOT4")){
                dataList = aot40HistoryDayDataService.spaceDataByGrowth(city, "AOT40", year, crop, startPeriod, endPeriod);
            }else {
                dataList = aot40HistoryDayDataService.spaceDataByGrowth(city, "max_8h_O3", year, crop, startPeriod, endPeriod);
            }

            for (Aot40HistoryDayDataHsxt i:
                    dataList) {
                HashMap<String, Object> data = new HashMap<>();
                data.put("city", i.getCity());
                data.put("district", i.getCounty());
                data.put("longitude", null);
                data.put("latitude", null);

                if(element.equals("AOT4")){
                    data.put("AOT4", i.getAot40());
                }else if(element.equals("24h_8h_O3")){
                    data.put("24h_8h_O3", i.getMax8hO3());
                }
                result.put(i.getDate(), data);
            }
        }catch (DataAccessException e){
            e.printStackTrace();
            return R.error().message("数据库访问出错");
        } catch (Exception e){
            e.printStackTrace();

            return R.error().message("出现了未知错误");
        }

        return R.ok().data("data", result);
    }

    @GetMapping("/O3-day-data")
    @ApiOperation("获取臭氧对农作物影响指标之逐日数据")
    public R Aot40OrO3ByGrowthForDay(@RequestParam("city") String city,
                                        @RequestParam("district") String district,
                                        @RequestParam("element") String element,
                                        @RequestParam("year") String year,
                                        @RequestParam("crop") String crop,
                                        @RequestParam("startPeriod") String startPeriod, @RequestParam("endPeriod") String endPeriod){
        TreeMap<String, Object> result = new TreeMap<>();
        try {
            ArrayList<Aot40HistoryDayDataHsxt> dataList;
            if(element.equals("AOT4")){
                dataList = aot40HistoryDayDataService.spaceDataForDay(city, district, "AOT40", year, crop, startPeriod, endPeriod);
            }else {
                dataList = aot40HistoryDayDataService.spaceDataForDay(city, district, "max_8h_O3", year, crop, startPeriod, endPeriod);
            }
            System.out.println(dataList);
            for (Aot40HistoryDayDataHsxt i:
                    dataList) {

                if(element.equals("AOT4")){
                    result.put(i.getDate(), i.getAot40());
                }else if(element.equals("24h_8h_O3")){
                    result.put(i.getDate(), i.getMax8hO3());
                }
            }
            System.out.println(result);
        }catch (DataAccessException e){
            e.printStackTrace();
            return R.error().message("数据库访问出错");
        } catch (Exception e){
            e.printStackTrace();
            return R.error().message("出现了未知错误");
        }

        return R.ok().data("data", result);
    }

    @GetMapping("/O3-space-data_")
    @ApiOperation("获取臭氧对农作物影响指标空间数据")
    public R Aot40OrO3ByGrowth_(@RequestParam("city") String city,
                               @RequestParam("year") String year,
                               @RequestParam("crop") String crop,
                               @RequestParam("startPeriod") String startPeriod, @RequestParam("endPeriod") String endPeriod){


        HashMap<String, String[]> countyToLatLon = new HashMap<>();


        // 不能写死得从数据库查
        // 根据city查区县 和 经纬度

//        QueryWrapper<Aot40HistoryDayDataHsxt> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("city", city);
//        List<Aot40HistoryDayDataHsxt> hsxts = aot40HistoryDayDataService.list(queryWrapper);
//        ArrayList<String> countys = new ArrayList<>();
//        for (Aot40HistoryDayDataHsxt hsxt : hsxts) {
//            if (! countys.contains(hsxt.getCounty())) {
//                countys.add(hsxt.getCounty());
//            }
//        }

        //这太慢了，得SQL语句查

        List<Map<String, Object>> tempList1 = aot40HistoryDayDataService.countyToLonLat(city);

        for (Map<String, Object> stringStringMap : tempList1) {
            countyToLatLon.put(stringStringMap.get("station_name").toString(), new String[]{stringStringMap.get("lon").toString(), stringStringMap.get("lat").toString()});
        }


        // 查经纬度

//        ArrayList<WeatherStationInfo> weatherStationInfos = aot40HistoryDayDataService.lonLatInfo();
//        for (WeatherStationInfo weatherStationInfo : weatherStationInfos) {
//            Double lon = Double.valueOf(weatherStationInfo.getLon());
//            Double lat = Double.valueOf(weatherStationInfo.getLat());
//            countyToLatLon.put(weatherStationInfo.getStationName(), new Double[]{lon, lat});
//        }




        // 指定生长周期的时间
        ArrayList<ArrayList<Aot40HistoryDayDataHsxt>> tempList = new ArrayList<>();
        String[] timeRange = wheatCornGrowthService.getTimeRangeImprove(city, year, crop, startPeriod, endPeriod);

        String startDate = timeRange[0];
        String endDate = timeRange[1];

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate start = LocalDate.parse(startDate, formatter);
        LocalDate end = LocalDate.parse(endDate, formatter);

        List<String> dateList = new ArrayList<>();

        // Loop through the date range
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date.format(formatter));
        }


        // 完全没有必要
//        for (String county : countys) {
//
//            // 根据startDate， endData 查 aot40_history_day_data_hsxt 表
//            QueryWrapper<Aot40HistoryDayDataHsxt> wrapper1 = new QueryWrapper<>();
//            wrapper1.eq("city", city);
//            wrapper1.eq("county", county);
//            wrapper1.between("date", startDate, endDate);
//
//            ArrayList<Aot40HistoryDayDataHsxt> list = (ArrayList<Aot40HistoryDayDataHsxt>) aot40HistoryDayDataService.list(wrapper1);
//            tempList.add(list);
//        }

        QueryWrapper<Aot40HistoryDayDataHsxt> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("city", city);
        wrapper1.between("date", startDate, endDate);
        ArrayList<Aot40HistoryDayDataHsxt> list = (ArrayList<Aot40HistoryDayDataHsxt>) aot40HistoryDayDataService.list(wrapper1);


//        ArrayList<String> dataList = new ArrayList<>();
//        ArrayList<Aot40HistoryDayDataHsxt> l;
//        if (tempList.get(0).size() != 0) {
//            l = tempList.get(0);
//        } else {
//            l = tempList.get(1);
//        }
//        for (Aot40HistoryDayDataHsxt s : l) {
//            dataList.add(s.getDate());
//        }



        TreeMap<String, ArrayList<Temp>> res = new TreeMap<>();

        for (String s : dateList) {
            ArrayList<Temp> temps = new ArrayList<>();
            for (Aot40HistoryDayDataHsxt aot40HistoryDayDataHsxt : list) {
                try {
                    if (s.equals(aot40HistoryDayDataHsxt.getDate())) {
                        Temp temp = new Temp();
                        temp.city = aot40HistoryDayDataHsxt.getCity();
                        temp.district = aot40HistoryDayDataHsxt.getCounty();
                        String[] doubles = countyToLatLon.get(temp.district);
                        temp.latitude = doubles[1];
                        temp.longitude = doubles[0];
                        temp.aot40 = String.valueOf(aot40HistoryDayDataHsxt.getAot40());
                        temp.max8hO3 = String.valueOf(aot40HistoryDayDataHsxt.getMax8hO3());
                        temps.add(temp);
                    }
                } catch (Exception ignored) {
                }
            }
            res.put(s, temps);
        }
        return R.ok().data("data", res);
    }

    private static class Temp implements Serializable {
        private String city;
        private String district;
        private String longitude;
        private String latitude;
        private String aot40;
        private String max8hO3;

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getDistrict() {
            return district;
        }

        public void setDistrict(String district) {
            this.district = district;
        }

        public String getLongitude() {
            return longitude;
        }

        public void setLongitude(String longitude) {
            this.longitude = longitude;
        }

        public String getLatitude() {
            return latitude;
        }

        public void setLatitude(String latitude) {
            this.latitude = latitude;
        }

        public String getAot40() {
            return aot40;
        }

        public void setAot40(String aot40) {
            this.aot40 = aot40;
        }

        public String getMax8hO3() {
            return max8hO3;
        }

        public void setMax8hO3(String max8hO3) {
            this.max8hO3 = max8hO3;
        }
    }

    @GetMapping("/O3-day-data_")
    @ApiOperation("获取臭氧对农作物影响指标之逐日数据")
    public R Aot40OrO3ByGrowthForDay_(@RequestParam("city") String city,
                                     @RequestParam("district") String district,
                                     @RequestParam("element") String element,
                                     @RequestParam("year") String year,
                                     @RequestParam("crop") String crop,
                                     @RequestParam("startPeriod") String startPeriod, @RequestParam("endPeriod") String endPeriod){

        // 找startDate和endData
        String startDate = null;
        String endDate = null;

        String[] timeRange = wheatCornGrowthService.getTimeRange(city, year, crop, startPeriod, endPeriod);
        startDate = timeRange[0];
        endDate = timeRange[1];


        // 根据startDate， endData 查 aot40_history_day_data_hsxt 表
        QueryWrapper<Aot40HistoryDayDataHsxt> wrapper1 = new QueryWrapper<>();

        wrapper1.eq("city", city);
        wrapper1.eq("county", district);
        wrapper1.between("date", startDate, endDate);

        ArrayList<Aot40HistoryDayDataHsxt> list = (ArrayList<Aot40HistoryDayDataHsxt>) aot40HistoryDayDataService.list(wrapper1);

        TreeMap<String, Object> res = new TreeMap<>();
        for (Aot40HistoryDayDataHsxt aot40HistoryDayDataHsxt : list) {
            if (element.equals("AOT40")) {
                res.put(aot40HistoryDayDataHsxt.getDate(), aot40HistoryDayDataHsxt.getAot40());
            } else {
                res.put(aot40HistoryDayDataHsxt.getDate(), aot40HistoryDayDataHsxt.getMax8hO3());
            }
        }
        return R.ok().data(res);
    }
}

